package app.util;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import org.h2.jdbc.JdbcSQLIntegrityConstraintViolationException;
import org.h2.jdbc.JdbcSQLSyntaxErrorException;
import org.h2.tools.RunScript;

/**
 * 创建h2数数据库文件以及数据库
 */
public class H2ConnTest01 {
    /**
     * 以嵌入式(本地)连接方式连接H2数据库
     */
    //private static final String JDBC_URL = "jdbc:h2:C:/H2/abc";
    /**
     * 使用TCP/IP的服务器模式(远程连接)方式连接H2数据库(推荐)
     */
//    private static final String JDBC_URL = "jdbc:h2:tcp://127.0.0.1/C:/H2/user";
	/*
	//内嵌式主要有两种，一种是内存模式，这种模式不会落地持久化，所以比较适合测试，关闭连接后数据库就清空，只需要添加
	private static final String JDBC_URL = "jdbc:h2:mem:DBName;DB_CLOSE_DELAY=-1";
	//另外一种是持久化模式，这种模式会将数据落地持久化到指定的目录，生成与数据库同名的.mv.db文件
	private static final String JDBC_URL = "jdbc:h2:tcp://localhost/~/test”；
	 */
    public static void main(String[] args) throws Exception {
    	 // delete the database named 'test' in the user home directory
        //DeleteDbFiles.execute("~", "test", true);
        Class.forName("org.h2.Driver");
        Connection conn = DriverManager.getConnection("jdbc:h2:/paiban112233");
        Statement stat = conn.createStatement();
        // this line would initialize the database
        // from the SQL script file 'init.sql'
        // stat.execute("runscript from 'init.sql'");
        ResultSet rs;
        
        try {
        	InputStream in = H2ConnTest01.class.getResourceAsStream("tables_h2.sql");
            RunScript.execute(conn, new InputStreamReader(in, StandardCharsets.UTF_8));
            in.close();
		}catch (Exception e) {
			e.printStackTrace();
		}
        rs = stat.executeQuery("select * from QRTZ_CALENDARS");
        while (rs.next()) {
            System.out.println(rs.getString("SCHED_NAME"));
        }
        stat.close();
        conn.close();
    }
}